package com.example.j2025_11_10.interceptor;

import com.example.j2025_11_10.Model.UserInfo;
import com.example.j2025_11_10.constant.Constants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
//目标方法执行前
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        log.info("LoginInterceptor ⽬标⽅法执⾏前执⾏..");
        HttpSession session = request.getSession();
        if (!checkUser(session)){
            response.setContentType("text/html;charset=utf-8");
            response.setStatus(401);
            String msg = "用户未登录";
            response.getOutputStream().write(msg.getBytes("UTF-8"));
            return false;
        }
        return true;
        }
//目标方法执行后
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("LoginInterceptor ⽬标⽅法执⾏后执⾏..");
    }

    public Boolean checkUser(HttpSession session){
        if (session == null || session.getAttribute(Constants.SESSION_USER_KEY)==null){
            log.warn("用户未登录");
            //用户未登录
            return false;
        }
        UserInfo userInfo = (UserInfo)session.getAttribute(Constants.SESSION_USER_KEY);
        if (userInfo==null || userInfo.getId()<=0){
            log.warn("用户未登录");
            return false;
        }
        log.info("用户已登录");
        return true;
    }
//图形界面执行后
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
//    }
}
